from typing import List
from PyQt5.QtGui import QPainter, QPaintEvent, QColor
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt, QRectF
import math
import numpy as np


class CanvasWidget(QWidget):
    histogramData: np.ndarray = None  # 灰度直方图数据,除以最大值归一化后，1xn 的数组
    color = QColor(255, 255, 255)  # 画笔颜色

    def __init__(self, parent):
        super().__init__(parent)
        self.initUI()

    def initUI(self):
        # self.setStyleSheet("background-color: #0000FF;")
        # self.setAttribute(Qt.WA_StyledBackground, True)
        self.setWindowFlags(Qt.FramelessWindowHint)

    def paintEvent(self, event: QPaintEvent):
        if self.histogramData is None:
            return
        data = self.histogramData
        color = self.color
        w, h = self.width(), self.height()
        padding = (h/40, h/40, 0, 0)  # 上下左右
        w2 = w - padding[2] - padding[3]
        h2 = h - padding[0] - padding[1]
        # 绘制 直方图
        col = self.histogramData.shape[0]   # 数据列数
        spin = w2 / 256 * math.ceil(256 / col)  # 界面步进
        height = h2    # 直方图 最大高度

        qp = QPainter()
        qp.begin(self)
        for i in range(0, col-1):
            rect = QRectF(padding[2] + i * spin, padding[0] + (1-data[i]) * height, spin, data[i] * height)   # 左上角x,yRate w,h
            qp.fillRect(rect, color)
        # pen = QPen(Qt.blue, 5, Qt.SolidLine)
        # qp.setPen(pen)
        # 绘制最后一个数据项
        i = col - 1
        spin = w / 256 * (256 % col)  # 步进+
        rect = QRectF(w2 + padding[2] - spin, padding[0] + (1 - data[i]) * height, spin, data[i] * height)  # 左上角x,yRate w,h
        qp.fillRect(rect, self.color)
        qp.end()
